<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>

<head>
<title>Tic Tac Toe</title>
<style>

body{
	padding:100px 300px;
	background-image: url('pic.gif');
}

td {
	height: 20px;
	width: 20px;
	border: 1px solid black;
	padding: 0px;
	margin-right: 0px;
	color:white;
}
</style>

<link type="text/css" href="jquery/jquery-ui-1.8.16.custom.css" rel="stylesheet" />			
<script LANGUAGE="JavaScript" SRC="jquery/jquery-1.7.min.js"></script>
<script LANGUAGE="JavaScript" SRC="jquery/jquery-ui-1.8.16.custom.min.js"></script>

<script type="text/javascript">
	var count = 0;
	var user = 0;
	
	window.onload = function(e) {
		$('#table').hide()
		$('#startButton').click(start)
		$("td").click(meth)
		
	}	
	
	function start(){
		$('#startButton').hide();
		clearImagesOfSquares()
		clearMessage()
		$('#table').show()
		$.ajax({
			url: '/tictactoe/startgame.c'
		});
	}
	
	function clearImagesOfSquares(){
		$('td').each(function (i) {
			this.style.backgroundImage="None"
	    });
	}
	
	function clearMessage(){
		$("#output").html("")
	}
	
	function meth(event) {
		var backgroundStyle = ""
		if(count%2==0){
			user = 1
			backgroundStyle="url('x.gif') no-repeat";
		}else{					
			user = 2;
			backgroundStyle="url('o.gif') no-repeat";
		}  
		
		$.ajax({
			url: '/tictactoe/tictac.c?userId=' + user + '&coid=' + event.target.id,
			success: function( data ) {
				var response = jQuery.parseJSON(data)
				$("#output").html(response.message)
				if(response.coordinateValid == 'true'){
					event.target.style.background=backgroundStyle;
					count++;
				}
				if(response.endOfGame == 'true'){
					count=0;	
					$( '#dialog-modal').dialog({
						height: 140,
						title: response.message,
						modal: true,
						buttons: {
							RestartGame: function() {
								start();
								$( this ).dialog( "close" );
							}
						}
					});

				}
			},
			error: function(jqXHR, textStatus, errorThrown) {
				alert(textStatus)
				alert(errorThrown)
			}
		});
							  
	}
	
	
</script>

</head>
<body>
	<h1>Tic Tac Toe</h1>
	<p id="output"></p>
	<div id="dialog-modal" title="Basic modal dialog">
	</div>
	<input id="startButton" type="button" value="Start Game" />
	<table id="table" height="200" width="200" cellspacing="0" cellpadding="0">
		<tr>
			<td id="8">d </td>
			<td id="7">d </td>
			<td id="6">d </td>
		</tr>

		<tr>
			<td id="5">d </td>
			<td id="4">d </td>
			<td id="3">d </td>
		</tr>

		<tr>
			<td id="2">d </td>
			<td id="1">d </td>
			<td id="0">d </td>
		</tr>

	</table>


</body>


</html>